package com.tanhua.admin.listeners;

import com.tanhua.autoconfig.template.AliyunGreenTemplate;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.model.mongo.Movement;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class AuditListener {

    @DubboReference
    private MovementApi movementApi;

    @Autowired
    private AliyunGreenTemplate template;

    @RabbitListener(
            bindings = @QueueBinding(
                    value=@Queue(
                            value = "tanhua.audit.queue"
                    ),
                    exchange=@Exchange(
                            value = "tanhua.audit.exchange",
                            type = ExchangeTypes.TOPIC
                    ),
                    key="audit.movement"
            )
    )
    public void audit(String movementId) throws Exception {
        //1、根据动态id，查询动态对象
        Movement movement = movementApi.findById(movementId);
        if(movement != null && movement.getState()==0) {
            //2、获取动态的文本内容和图片内容
            String text = movement.getTextContent();//文本
            List<String> images = movement.getMedias();//图片
            //3、调用阿里云工具，进行文本和图片审核
            Map<String, String> textScan = template.greenTextScan(text);
            String textSug = textScan.get("suggestion");
            Map<String, String> imageScan = template.imageScan(images);
            String imaSug = imageScan.get("suggestion");
            //4、判断文本和图片是都全部审核成功
            Integer state = 0; //动态状态
            if(textSug.equals("pass") && imaSug.equals("pass")) {
                state=1; //内容没问题
            }else if(textSug.equals("block") || imaSug.equals("block")) {
                state=2;
            }
            movementApi.updateState(movementId,state);
        }

    }
}
